package com.gitee.cui.server.handler;

import com.gitee.cui.common.common.exception.InvalidFrameException;
import com.gitee.cui.server.server.ServerSession;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.io.IOException;

/**
 * 服务端异常处理器
 *
 * @author cuiqingqiang
 * @version 1.0
 * @date 2021-10-27 23:11
 **/
@Slf4j
@ChannelHandler.Sharable
@Service
public class ServerExceptionHandler extends ChannelInboundHandlerAdapter {
	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		if (cause instanceof InvalidFrameException) {
			cause.printStackTrace();
			log.error(cause.getMessage());
		}
		if (cause instanceof IOException) {
			log.error(cause.getMessage());
			log.error("客户端连接已经关闭，这里需要做下线处理");
			ServerSession.closeSession(ctx);
		} else {
			cause.printStackTrace();
			log.error(cause.getMessage());
		}
	}

	@Override
	public void channelInactive(ChannelHandlerContext ctx) throws Exception {
		ServerSession.closeSession(ctx);
	}

	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		ctx.flush();
	}
}
